import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';

import 'package:bruno/bruno.dart';
import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';
import 'package:sph_driver/AppConfig/ShowDialog.dart';

import '../../AppConfig/Config.dart';
import '../../AppConfig/LocalStorage.dart';
import '../../Tabbar/TabbarView.dart';
import '../../http/NoLoadingPostApi.dart';
import '../../http/api.dart';
import '../../l10n/messages.dart';
import 'package:image/image.dart' as img;
class FleetDetails extends StatefulWidget {
  const FleetDetails({super.key, required this.fleetMap, required this.captainId});
  final Map fleetMap;
  final String captainId;
  @override
  State<FleetDetails> createState() => _FleetDetailsState();
}

class _FleetDetailsState extends State<FleetDetails> {
  final ImagePicker picker = new ImagePicker();
  File? _userImage;
  String titleText="张大帅的车队";
  String describeText="";
  Map fleetData={};
  String handPath="";
  String driverId="";
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    fleetData=widget.fleetMap;
    titleText=fleetData['name'];
    if(fleetData['description']!=null)
    describeText=fleetData['description'];
    getDriverId();
  }

  void getDriverId()async{
    String? id =await UserIdManager.getUserID();
    setState(() {
      driverId=id!;
    });

  }

   //解散车队
  void deleFleetAction()async{
    String? token = await TokenManager.getToken();
    LoadingDialog.show(context);
    dio.interceptors.add(InterceptorsWrapper(
        onRequest: (options, handler) {
          options.headers["satoken"] = token;
          return handler.next(options);
        }
    ));
    dio.post(
      MyServiceUrl.header +
          'api/auth/driver/fleet/delete',
      data:    [{"id":fleetData['id']}],
      options: Options(
        sendTimeout: Duration(seconds: 2),
        receiveTimeout: Duration(seconds: 50),
      ),
      onSendProgress: (a, b) => print('send ${a / b}'),
      onReceiveProgress: (a, b) =>
          print('received ${a / b}'),
    )
        .then((r) {
      setState(() {
        print(r);
        Map<String, dynamic> jsonMap = json.decode(
            r.toString());
        // 获取code和data
        String code = jsonMap['code'].toString();
        LoadingDialog.hide(context);
        if (code == "200") {
          BrnToast.show("车队已解散", context);
          Navigator.of(context).pushAndRemoveUntil(
              MaterialPageRoute(builder: (builder) {
                return TabbarView(pateIndex: 3,);
              }), (route) => route == null);
        } else {
          BrnToast.show(jsonMap['msg'], context);
        }
      });
    }).catchError((error) {
      BrnToast.show(error.toString(), context);
      print(error);
      LoadingDialog.hide(context);
      ;
    });

  }
  void printImageMemorySize(File imageFile) {
    List<int> imageBytes = imageFile.readAsBytesSync();
    print('Original Image Memory Size: ${imageBytes.length} bytes');
  }

  Future<void> compressImage(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    img.Image image = img.decodeImage(Uint8List.fromList(imageBytes))!;

    // Adjust the quality and size as needed
    img.Image compressedImage = img.copyResize(image, width: 1024);

    List<int> compressedBytes = img.encodeJpg(compressedImage, quality: 80);

    // Create a new File for the compressed image
    File compressedFile = File('${imageFile.path}_compressed.jpg');
    await compressedFile.writeAsBytes(compressedBytes);

    print('Compressed Image Size: ${compressedBytes.length} bytes');

    convertToBase64(compressedFile);
  }

  Future<void> convertToBase64(File imageFile) async {
    List<int> imageBytes = await imageFile.readAsBytes();
    String base64String = base64Encode(imageBytes);
    uploadSingleFile(base64String);

  }
  Future<void> uploadSingleFile(String fileData) async {
    NoLoadingApiManager.postData(
      context,
      "api/system/dev/file/uploadSingleFile",
      {'type':'DriverAvatar',
        'fileData':fileData,
        "fileName":fleetData['id'],
        "fileFormat":"jpg"},
          (responseData)  {
        setState(() {
          handPath=responseData['data'].toString();
        });

      },
    );
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    var messages = AppLocalizations.of(context)!;
    return Scaffold(
        backgroundColor: MyColors.backgreyColor,
        appBar: AppBar(
        backgroundColor: Colors.white,
        centerTitle: true,
          leading: IconButton(
            icon: Icon(Icons.arrow_back_ios, color: Colors.black),
            onPressed: () => Navigator.pop(context,"success"),
          ),
        title: Text("车队详情",style: TextStyle(color: Colors.black,fontWeight: FontWeight.w300,fontSize: 16.sp),),
        ),
      body: Column(
    children: [
    Expanded(child:ListView(
      children: [
        Container(

          margin: EdgeInsets.only(left: 10.w,right: 10.w,top: 8.h),
          padding: EdgeInsets.all(10.w),
          decoration: BoxDecoration(
              color:Colors.white,
              borderRadius: BorderRadius.all(Radius.circular(10))),
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text("车队头像",style: TextStyle(color: Colors.black,fontSize: 14.sp),),


                  GestureDetector(
                    child:   Container(
                      width: 50.w,
                      height: 50.h,
                      child: _userImage!=null?  CircleAvatar(
                        radius: 15,
                        backgroundImage: FileImage(_userImage!),
                      ) :fleetData['avatarPath']!=null&&fleetData['avatarPath']!=""?
                      CircleAvatar(
                        radius: 15,
                        backgroundImage: NetworkImage(MyServiceUrl.imgHeader +fleetData['avatarPath']),
                      ) :
                            CircleAvatar(
                        radius: 15,
                        backgroundImage: AssetImage("lib/Images/login/默认头像.jpeg"),
                      ),
                    ),
                    onTap: (){
                      if(driverId==widget.captainId)
                      showModalBottomSheet(context: context, builder: (BuildContext context) {
                        return Container(
                            decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(10.0),
                            ),
                          child:
                          Stack(

                            children: [

                              Column(
                                mainAxisSize: MainAxisSize.min,
                                mainAxisAlignment:MainAxisAlignment.center,

                                children:[

                                  SizedBox(height: 8.h,),
                                  Row(
                                    mainAxisAlignment:MainAxisAlignment.end,
                                    children: [
                                      IconButton(onPressed: (){
                                        Navigator.of(context).pop();
                                      }, icon:Icon(Icons.close,color: MyColors.textColor,)),
                                    ],
                                  ),

                                  Text(messages["上传照片"],style: TextStyle(color: Colors.black,fontWeight: FontWeight.w600,fontSize: 18.sp),),
                                  SizedBox(height: 18.h,),
                                  Row(
                                    children: [
                                      SizedBox(width: 38.w,),
                                      GestureDetector(
                                        child:   Column(
                                          children: [
                                            Image.asset("lib/Images/Authentication/相册icon.png",width:35.w ,height: 35.h,),
                                            Text(messages["相册"],style: TextStyle(color: Colors.black),),

                                          ],

                                        ),
                                        onTap: ()async{
                                          Navigator.of(context).pop();
                                          final pickedFile = await picker.pickImage(source: ImageSource.gallery);

                                          if (pickedFile != null) {

                                            setState(() {
                                              _userImage = File(pickedFile.path);
                                              printImageMemorySize(_userImage!);
                                              print(_userImage);
                                              compressImage(_userImage!);


                                            });
                                          }
                                        },
                                      ),

                                      SizedBox(width: 38.w,),
                                      GestureDetector(
                                        child: Column(
                                          children: [
                                            Image.asset("lib/Images/Authentication/拍照icon.png",width:35.w ,height: 35.h,),
                                            Text(messages["拍照"],style: TextStyle(color: Colors.black),),

                                          ],

                                        ),
                                        onTap: ()async{
                                          Navigator.of(context).pop();
                                          final pickedFile = await picker.pickImage(source: ImageSource.camera);

                                          if (pickedFile != null) {
                                            setState(() {

                                              _userImage = File(pickedFile.path);
                                              printImageMemorySize(_userImage!);
                                              print(_userImage);
                                              compressImage(_userImage!);


                                            });
                                          }
                                        },
                                      ),

                                    ],
                                  ),
                                  SizedBox(height: 20.h,),
                                ],

                              ),

                            ],

                          ),
                        );


                      });
                    },
                  ),

                ],
              ),
              SizedBox(height: 10.h,),
              Container(height: 1.h,color: MyColors.backgreyColor,),
              SizedBox(height: 10.h,),
              GestureDetector(
                child:  Container(
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text("车队名称",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                      Container(
                        width: screenSize.width/1.8,
                        child:Text(titleText,textAlign: TextAlign.right,style: TextStyle(color: Colors.black,fontSize: 14.sp),),

                      ),
                    ],
                  ),
                ),

                onTap: () async {
                  if(driverId==widget.captainId){
                    final result = await showModalBottomSheet(
                        context: context,
                        isScrollControlled: true,

                        builder: (BuildContext context) {
                          return editMessageSheeet(type: 1, textValue: titleText,);
                        }
                    );
                    if (result != null) {
                      setState(() {

                        titleText=result;
                        print(titleText);
                      });
                    };
                  }

                }
              ),

              SizedBox(height: 10.h,),
              Container(height: 1.h,color: MyColors.backgreyColor,),
              SizedBox(height: 10.h,),
              GestureDetector(
                  child:  Row(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      children: [
                        Text("车队描述",style: TextStyle(color: Colors.black,fontSize: 14.sp),),
                        Container(
                          width: screenSize.width/1.8,
                          child:Text(describeText==""?"请输入车队描述":describeText,textAlign: TextAlign.right,style: TextStyle(color: describeText==""? MyColors.hintColor:Colors.black,fontSize: 14.sp),),

                        )
                      ],
                    ),


                  onTap: () async {
                    if(driverId==widget.captainId) {
                      final result = await showModalBottomSheet(
                          context: context,
                          isScrollControlled: true,

                          builder: (BuildContext context) {
                            return editMessageSheeet(type: 2, textValue: describeText,);
                          }
                      );
                      if (result != null) {
                        setState(() {
                          describeText = result;
                          print(describeText);
                        });
                      };
                    }
                  }
              ),

            ],
          ),
        )
      ],
    ),),
      if(driverId==widget.captainId)
      Container(
        height:  80.h,
        color: Colors.white,
        child:  Row(
          children: [
            GestureDetector(
              child: Container(

                decoration: BoxDecoration(
                    border: Border.all(
                      color: MyColors.themeColor, // Set the color of the border
                      width: 1.0.w, // Set the width of the border
                    ),

                    color:Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(30))),
                child:Center(
                  child:   Text("解散车队",style: TextStyle(fontSize: 16.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),
                ),
                width: (screenSize.width-40)/2,
                height: 40.h,
              ),
              onTap: (){
                showModalBottomSheet(
                  context: context,
                  builder: (BuildContext context) {
                    return Container(
                      decoration: BoxDecoration(
                          color:Colors.white,
                          borderRadius: BorderRadius.all(Radius.circular(30))),
                      padding: EdgeInsets.all(10.w),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          SizedBox(height: 10.h,),
                          Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: [
                              Text("您确定要解散车队吗？",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
                              GestureDetector(
                                child: Icon(Icons.close,color: MyColors.textColor,),
                                onTap: (){
                                  Navigator.of(context).pop();
                                },
                              ),
                            ],

                          ),
                          SizedBox(height: 8.h,),
                          Text("解散车队后，平台为您提供的车队长专属功能和特权都将同步取消。包括但不限于以下几种:车队/人员管理、满运宝货源分配、多线路找货、一键分单、同步轨迹、运费代收、账单管理、排班调度。"
                            ,style: TextStyle(color: MyColors.textColor,fontSize: 12.sp),),
                          SizedBox(height: 8.h,),
                          Row(
                              children: [
                                GestureDetector(
                                  child: Container(

                                    decoration: BoxDecoration(
                                        border: Border.all(
                                          color: MyColors.themeColor, // Set the color of the border
                                          width: 1.0.w, // Set the width of the border
                                        ),

                                        color:Colors.white,
                                        borderRadius: BorderRadius.all(Radius.circular(30))),

                                    child:Center(
                                      child:   Text("确定解散",style: TextStyle(fontSize: 12.sp,color: MyColors.themeColor,fontWeight: FontWeight.w600),),
                                    ),

                                    width: (screenSize.width-40)/2,
                                    height: 40.h,
                                  ),
                                  onTap: (){
                                  deleFleetAction();
                                  },
                                ),
                                SizedBox(width: 8.w,),
                                GestureDetector(
                                  child: Container(

                                    decoration: BoxDecoration(
                                        color:MyColors.themeColor,
                                        borderRadius: BorderRadius.all(Radius.circular(30))),

                                    child:Center(
                                      child:   Text("再考虑一下",style: TextStyle(fontSize: 12.sp,color: Colors.white,fontWeight: FontWeight.w600),),
                                    ),

                                    width: (screenSize.width-40)/2,
                                    height: 40.h,
                                  ),
                                  onTap: (){
                                    Navigator.of(context).pop();
                                  },
                                ),
                              ]
                          ),
                          SizedBox(height: 30.h,),
                        ],
                      ),
                    );
                  },
                );
              },
            ),
            SizedBox(width: 8.w,),
            GestureDetector(
              child: Container(
                decoration: BoxDecoration(
                    color:MyColors.themeColor,
                    borderRadius: BorderRadius.all(Radius.circular(30))),

                child:Center(
                  child: Text("保存",style: TextStyle(fontSize: 16.sp,color: Colors.white,fontWeight: FontWeight.w600),),
                ),
                width: (screenSize.width-40)/2,
                height: 40.h,
              ),
              onTap: (){
                print(handPath);
                ApiManager.postData(
                  context,
                  "api/auth/driver/fleet/edit",
                  {'id':fleetData['id'],
                    "name":titleText,
                    "avatarPath":handPath,
                    "description":describeText
                  },
                      (responseData)  {
                        BrnToast.show("保存成功", context);
                        Navigator.pop(context,"success");

                  },
                );

              },
            ),
          ],
          mainAxisAlignment: MainAxisAlignment.center,
        ),
      ),
        ]
      )
    );
  }
}

class editMessageSheeet extends StatefulWidget {
  const editMessageSheeet({super.key, required this.type, required this.textValue});
  final int type;
  final String textValue;
  @override
  State<editMessageSheeet> createState() => _editMessageSheeetState();
}

class _editMessageSheeetState extends State<editMessageSheeet> {
  String textValue="";
  TextEditingController _textController = TextEditingController();
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    textValue=widget.textValue;
    if(textValue!="")
      _textController.text = textValue;
  }
  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;
    return Container(
      width: screenSize.width,
      padding: EdgeInsets.only(top: 15.h),
        decoration: BoxDecoration(
            color:Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10))),
      height: 400.h,
      child: Column(
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceAround,
            children: [
              TextButton(onPressed: (){
                Navigator.pop(context);
              }, child: Text("取消     ",style: TextStyle(color: Colors.black,fontSize: 14.sp),)),
              Text(widget.type==1?"车队名称":"车队描述",style: TextStyle(color: Colors.black,fontSize: 16.sp,fontWeight: FontWeight.w600),),
              TextButton(onPressed: (){
                Navigator.pop(context,textValue);
              }, child: Text("     确定",style: TextStyle(color: MyColors.themeColor,fontSize: 14.sp),)),
            ],

          ),
          Container(
            height: 40.h,
            padding: EdgeInsets.only(left: 10.w,right: 10.w),
            width: screenSize.width-50,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.all(Radius.circular(30))),
            child:  Container(
              width: screenSize.width-70.w,
              child: TextField(
                controller: _textController,
                decoration: InputDecoration(
                  border: InputBorder.none,
                  hintText: widget.type==1?'请输入车队名称':'请输入车队描述',
                  hintStyle:TextStyle(fontSize: 14.sp,color: MyColors.textColor),
                  filled: true,
                  fillColor: MyColors.backgreyColor,
                  // border: InputBorder.none,
                  alignLabelWithHint: true,
                  // contentPadding: EdgeInsets.symmetric(vertical: 6.0.h, horizontal: 0.0.w),
                ),
                textAlign: TextAlign.left,
                style: TextStyle(color: Colors.black),
                onChanged: (value) {
                  setState(() {
                    textValue=value;
                    print(value);
                  });
                },
              ),
            ),

          ),


        ],
      )
    );
  }
}
